package com.uu.safeguard.realm;

import com.uu.safeguard.common.Constant;
import com.uu.safeguard.service.MemberService;
import com.uu.safeguard.shirotoken.JwtToken;
import com.uu.safeguard.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;

/**
 * Shiro自定义JwtRealm授权认证器
 * @author cmt
 */
@Component
public class JwtRealm extends AuthorizingRealm {
    private static Logger logger = Logger.getLogger(JwtRealm.class);

    @Resource
    private MemberService memberService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    /**
     * 授权 获取用户的角色和权限
     *@param  [principals]
     *@return org.apache.shiro.authz.AuthorizationInfo
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取参数operatorMemberSn
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String operatorMemberSn = request.getHeader("operatorMemberSn");
        logger.info("授权:"+operatorMemberSn);
        //1. 从 PrincipalCollection 中来获取登录用户的信息
        String token=principals.toString();
        String sn = JwtUtil.getUserId(token);
        //2.添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }


    /**
     * 认证 判断token的有效性
     *@param
     *@return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String sn = JwtUtil.getUserId(token);
        logger.info("账号认证："+sn);
        if (sn == null) {
            logger.info("sn = null");
            throw new IncorrectCredentialsException("token无效，请重新登录");
        }
        //操作时校验的是非对称加密是否成立.
        if (!JwtUtil.verify(token, Constant.TOKEN_SECRET)) {
            logger.info("Token加密错误："+sn);
            throw new AuthenticationException("账号或密码错误");
        }
        //账号数据库比对
        LinkedHashMap<String, Object> member = memberService.findMemberBySn(sn);
        if (member == null) {
            logger.info("非本平台账户或无权限："+sn);
            throw new UnknownAccountException("非本平台账户或无权限");
        }
        LinkedHashMap<String, Object> memberRoleId = memberService.findMemberRoleId(sn);
        if (null == memberRoleId){
            logger.info("非本平台账户或无权限："+sn);
            throw new UnknownAccountException("非本平台账户或无权限");
        }
        //5. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token, token, this.getName());
        return info;
    }
    /**
     * 重写方法,清除当前用户的的 授权缓存
     * @param principals
     */
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    /**
     * 重写方法，清除当前用户的 认证缓存
     * @param principals
     */
    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    /**
     * 自定义方法：清除所有 授权缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    /**
     * 自定义方法：清除所有 认证缓存
     */
    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    /**
     * 自定义方法：清除所有的  认证缓存  和 授权缓存
     */
    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}
